package com.frx.fakeroutexposed.fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;

import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.frx.fakeroutexposed.R;
import com.frx.fakeroutexposed.events.ConfigEvent;
import com.frx.fakeroutexposed.events.GpsInfoEvent;
import com.frx.fakeroutexposed.events.MockFlagEvent;
import com.frx.fakeroutexposed.events.OpenGpsEvent;
import com.github.clans.fab.FloatingActionButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class MapViewFragments extends Fragment {

    /**
     * 开始模拟按钮
     */
    private FloatingActionButton fb_btn_begin_fake = null;
    /**
     * 停止模拟按钮
     */
    private FloatingActionButton fb_btn_stop_fake = null;
    /**
     * 加载轨迹按钮
     */
    private ImageButton btn_load_file = null;

    private TextView tv = null;
    /**
     * 显示轨迹名称的TextView
     */
    private TextView tvRouteName = null;
    /**
     * 模拟位置开关
     */
    private Switch sw_single_loc = null;
    /**
     * 模拟轨迹开关
     */
    private Switch sw_route = null;
    /**
     * 经度输入框
     */
    private EditText inputLongitude = null;
    /**
     * 纬度输入框
     */
    private EditText inputLatitude = null;
    /**
     * 海拔输入框
     */
    private EditText inputAltitude = null;

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    /**
     * 开关按钮的点击事件
     */
    CompoundButton.OnCheckedChangeListener mSWListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            //两个开关互斥,从而保证有一个是开启的
            switch (compoundButton.getId()) {
                case R.id.sw_single_loc:
                    sw_route.setChecked(!b);
                    changeInputEnabled(b);
                    break;
                case R.id.sw_route:
                    sw_single_loc.setChecked(!b);
                    changeInputEnabled(!b);
                    break;
                default:
                    break;
            }

        }
    };

    /**
     * 改变输入框的可用状态
     *
     * @param enable true,可用<br>
     *               false,不可用
     */
    private void changeInputEnabled(boolean enable) {
        inputLongitude.setEnabled(enable);
        inputLatitude.setEnabled(enable);
        inputAltitude.setEnabled(enable);

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //EventBus,注册为订阅者
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.map_view_fragment, container, false);



        fb_btn_begin_fake = (FloatingActionButton) view.findViewById(R.id.fab_btn_save_settings);
        fb_btn_stop_fake = (FloatingActionButton) view.findViewById(R.id.act_btn_stop);
        btn_load_file = (ImageButton) view.findViewById(R.id.btn_load_file);
        sw_single_loc = (Switch) view.findViewById(R.id.sw_single_loc);
        sw_route = (Switch) view.findViewById(R.id.sw_route);
        //经纬度,海拔输入框
        inputLongitude=(EditText)view.findViewById(R.id.inputLongitude);
        inputLatitude=(EditText)view.findViewById(R.id.inputLatitude);
        inputAltitude=(EditText)view.findViewById(R.id.inputAltitude);

        //设置按钮的监听事件
        fb_btn_begin_fake.setOnClickListener(btnClickListener);
        fb_btn_stop_fake.setOnClickListener(btnClickListener);
        btn_load_file.setOnClickListener(btnClickListener);
        sw_single_loc.setOnCheckedChangeListener(mSWListener);
        sw_route.setOnCheckedChangeListener(mSWListener);

        //fb_btn_begin_fake.setButtonColor(getResources().getColor(R.color.fab_material_grey_500));
        //fb_btn_begin_fake.setEnabled(false);
        //TODO 界面的布局,靠后吧.....设置按钮为不可见
        //fb_btn_begin_fake.setVisibility(View.GONE);
        //fb_btn_stop_fake.setButtonColor(getResources().getColor(R.color.fab_material_grey_500));
        //fb_btn_stop_fake.setEnabled(false);
        //设置按钮为不可见
        //fb_btn_begin_fake.hide(false);
        fb_btn_stop_fake.hide(false);
        //=============================
        tv = (TextView) view.findViewById(R.id.displayGPSinfoTX);
        tvRouteName = (TextView) view.findViewById(R.id.displayRouteNameTX);


        return view;
    }

    //=====================================
    private OnClickListener btnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            MockFlagEvent mockFlagEvent = new MockFlagEvent();

            switch (v.getId()) {
                case R.id.fab_btn_save_settings:
                    Log.d("Debug:", "开始按钮按下");
                    //开始模拟按钮的事件
                    mockFlagEvent.setStartHook(true);
                    //======================================
                    if(sw_single_loc.isChecked()){
                        if("".equals(inputLongitude.getText().toString())||
                                "".equals(inputLatitude.getText().toString())||
                                "".equals(inputAltitude.getText().toString())){
                            //如果经纬度为空,提示输入
                            Toast.makeText(getActivity(), getResources().getString(R.string.tips_input_data),
                                    Toast.LENGTH_SHORT).show();
                            return;

                        }
                        mockFlagEvent.setFlag_mock_single_loc(true);
                        mockFlagEvent.setLongitude(Double.valueOf(inputLongitude.getText().toString()));
                        mockFlagEvent.setLatitude(Double.valueOf(inputLatitude.getText().toString()));
                        mockFlagEvent.setAltitude(Double.valueOf(inputAltitude.getText().toString()));
                    }
                    if(sw_route.isChecked()){
                        if("".equals(tvRouteName.getText().toString())){
                            //提示选择轨迹文件
                            Toast.makeText(getActivity(), getResources().getString(R.string.tips_load_file),
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mockFlagEvent.setFlag_mock_single_loc(false);
                    }
                    //======================================
                    EventBus.getDefault().post(mockFlagEvent);

                    break;
                case R.id.act_btn_stop:
                    Log.d("Debug:", "停止按钮按下");
                    //停止模拟按钮的事件
                    mockFlagEvent.setStartHook(false);
                    EventBus.getDefault().post(mockFlagEvent);

                    break;

                case R.id.btn_load_file:
                    Log.d("Debug:", "载入按钮按下");
                    //载入轨迹
                    ListRouteFragment fragment = new ListRouteFragment();
                    fragment.show(getFragmentManager(), getString(R.string.dialog_title));
                    break;
                default:
                    break;
            }

        }
    };
    //=====================================

    /**
     * 改变按钮状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventChangeButtonStatues(ConfigEvent event) {
        //如果选择了轨迹文件,则将按钮调整为可用状态
        String fileName = event.getGpsDataFileNameFullPath();
        if (!((null == fileName) || "".equals(fileName))) {
            //fb_btn_begin_fake.setButtonColor(getResources().getColor(R.color.fab_material_blue_500));
            fb_btn_begin_fake.setEnabled(true);
            //播放按钮可见
            fb_btn_begin_fake.show(true);

        }
        //改变按钮的状态
        //TODO 按钮状态,不对,需要修正
        boolean flagBtn = event.isFlag_start_fake();
        if (flagBtn) {//开始模拟
            //fb_btn_stop_fake.setButtonColor(getResources().getColor(R.color.fab_material_blue_500));
            //停止按钮可见
            fb_btn_stop_fake.show(flagBtn);
            fb_btn_stop_fake.setEnabled(true);
            //fb_btn_begin_fake.setButtonColor(getResources().getColor(R.color.fab_material_grey_500));
            fb_btn_begin_fake.setEnabled(false);
            //fb_btn_load.setButtonColor(getResources().getColor(R.color.fab_material_grey_500));
            //fb_btn_load.setEnabled(false);
        } else {//停止模拟
            //fb_btn_stop_fake.setButtonColor(getResources().getColor(R.color.fab_material_grey_500));
            fb_btn_stop_fake.setEnabled(false);
            //fb_btn_load.setButtonColor(getResources().getColor(R.color.fab_material_blue_500));
            //fb_btn_load.setEnabled(true);
            this.clearTV();
        }
    }

    //----------------------------------------
    //将模拟的gps信息显示在界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventDisplayGPSinfo(GpsInfoEvent event) {
        String str = String.valueOf(event.getLongitude())
                + "," + String.valueOf(event.getLatitude())
                + "," + String.valueOf(event.getAltitude());
        //tv.setTextSize(20);
        tv.setText(str);
    }

    //----------------------------------------
    // 将模拟的GPS轨迹名显示在界面上
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventDisplayFileName(ConfigEvent event) {
        // 将GPS数据所在的文件的名字保存到SharedPreferences
        String fileName = event.getGpsDataFileNOEXName();
        if (!((null == fileName) || "".equals(fileName))) {
            // tvRouteName.setTextSize(20);
            tvRouteName.setText(fileName);
        }
    }

    //----------------------------------------
    //打开 GPS 设置界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOpenGPSSetting(OpenGpsEvent event) {
        //打开GPS设置界面
        if (event.isFlagOpenGPS()) {

            Toast.makeText(this.getActivity(), getResources().getString(R.string.str_tips_open_gps),
                    Toast.LENGTH_SHORT).show();

            //弹出对话框，让用户选择是否打开GPS设置界面
            AlertDialog.Builder dialog = new AlertDialog.Builder(this.getActivity());
            dialog.setMessage(getResources().getString(R.string.str_tips_open_gps));
            //确定按钮
            dialog.setPositiveButton(getResources().getString(R.string.str_btn_ok),
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            //取消按钮
            dialog.setNeutralButton(getResources().getString(R.string.str_btn_cancel), new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            });
            //显示对话框
            dialog.show();
        }
        if (event.isFlagLocationing()) {
            Toast.makeText(this.getActivity(), getResources().getString(R.string.str_tips_loc),
                    Toast.LENGTH_SHORT).show();
        }
    }
    //=====================================

    /**
     * 清除 TextView 的显示内容
     **/
    private void clearTV() {
        tv.setText("");
        tvRouteName.setText("");
    }

    //=====================================


    //=====================================
    @Override
    public void onDestroy() {
        Log.d("debug3.1","map fragment onDestroy");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onPause() {
        Log.d("debug3.1","map fragment onPause");
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        Log.d("debug3.1","map fragment onDestroyView");
        super.onDestroyView();
    }
}
